# This file is part of BlackArch Linux ( https://www.blackarch.org/ ).
# See COPYING for license details.

pkgname=lanmap2
pkgver=127.1197999
pkgrel=3
epoch=1
pkgdesc='Passive network mapping tool.'
arch=('x86_64' 'aarch64')
url='http://github.com/rflynn/lanmap2'
license=('GPL')
groups=('blackarch' 'blackarch-recon')
depends=('sqlite3' 'libpcap' 'php' 'graphviz' 'libbsd')
makedepends=('git' 'make' 'gcc-libs')
source=("git+http://github.com/rflynn/$pkgname.git")
sha512sums=('SKIP')
install="$pkgname.install"

pkgver() {
  cd $pkgname

  echo $(git rev-list --count HEAD).$(git rev-parse --short HEAD)
}

prepare() {
  cd $pkgname

  sed -i 's/DbFile\[\] = .*/DbFile\[\] = "db\/db";/g' src/report.c

  # Fix PHP.
  sed -i '1a\[ -z "$PHP_INI" ] && PHP_INI=/etc/php/php.ini' graph/graph.sh
  sed -i 's/^php/php -c $PHP_INI/' graph/graph.sh

  # add missing ldflags
  sed -i 's|LDFLAGS = -ggdb|LDFLAGS = -lbsd -ggdb|' tools/Makefile
  sed -i 's|LDFLAGS = -lpcap -lsqlite3|LDFLAGS = -lbsd -lpcap -lsqlite3|' \
    src/Makefile
  sed -i 's|#include <string.h>|#include <bsd/string.h>\n#include <string.h>|' \
    src/cap.c src/report.c src/util.h src/util.c src/dns.c
}

build() {
  cd $pkgname

  make all
}

package () {
  cd $pkgname

  install -dm 755 "$pkgdir/usr/bin"
  install -dm 755 "$pkgdir/usr/share/$pkgname/tools"
  install -dm 755 "$pkgdir/usr/share/doc/$pkgname/"

  install -m 755 "$srcdir/lanmap2/src/cap" "$pkgdir/usr/share/$pkgname"
  install -m 755 "$srcdir/lanmap2/tools/os-graph" \
    "$pkgdir/usr/share/$pkgname/tools"
  install -m 755 "$srcdir/lanmap2/tools/oui2insert" \
    "$pkgdir/usr/share/$pkgname/tools"

  cp -a graph web db img "$pkgdir/usr/share/$pkgname/"
  cp -a doc/* ref "$pkgdir/usr/share/doc/$pkgname/"

  cat > "$pkgdir/usr/bin/lanmap2-cap" << EOF
#!/bin/sh

if [ \$EUID != 0 ] ; then
  echo >&2 'run as root.'
  exit 1
fi

cd /usr/share/$pkgname
./cap
EOF

  chmod +x "$pkgdir/usr/bin/lanmap2-cap"

  cat > "$pkgdir/usr/bin/lanmap2-graph" << EOF
#!/bin/sh

if [ \$EUID != 0 ] ; then
  echo >&2 'run as root.'
  exit 1
fi

cd /usr/share/$pkgname/graph

# Fix PHP.
tmp=\`mktemp /tmp/lanmap.XXXXXXXX\`
cat /etc/php/php.ini > \$tmp
sed -i 's|open_basedir\s*=.*|&:/usr/share/graph|' \$tmp

PHP_INI=\$tmp ./graph.sh
EOF

  chmod +x "$pkgdir/usr/bin/lanmap2-graph"
}

